import React, {useEffect, useState} from 'react';
import {
  ActivityIndicator,
  Alert,
  Dimensions,
  Text,
  ToastAndroid,
  View,
  NativeModules,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import BoxManageView2 from '../views/BoxManageView2';
import withSerialPort from './SerialPortBoxPage';
import Row from '../components/Row';
import ColorButton from '../components/ColorButton';
import ModalViewUtil from '../components/ModalViewUtil';
import {get, getBaseURL, post} from '../http/http';
// import {Toast} from 'teaset';
import config from '../config/config';
import {useSelector} from 'react-redux';
import {ALERT_TYPE, Dialog, Toast} from 'react-native-alert-notification';
import LoginView from '../views/LoginView';
import moment from 'moment';
import ReactNativeBlobUtil from 'react-native-blob-util';
import {Dirs} from 'react-native-file-access';
import DeviceInfo from 'react-native-device-info';
import BlobUtils from '../utils/BlobUtils';
const WIN_WIDTH = Dimensions.get('window').width;
const {HKVisionDeviceModule} = NativeModules;
const BoxManagePage = props => {
  const [products, setProducts] = useState([]);
  const [manager, setManager] = useState(false);
  const user = useSelector(state => state.root.user);
  useEffect(() => {
    props.loadData();
    queryUserProducts();
  }, []);
  const materialCabinetId = props.route.params.materialCabinetId;

  const managerTakeProducts = () => {
    ModalViewUtil.showFromCenter(
      <LoginView
        userType={2}
        loginCancel={() => {
          ModalViewUtil.dismissBottomView();
        }}
        loginComplete={data => {
          ModalViewUtil.dismissBottomView();
        }}
      />,
    );
  };

  const queryUserProducts = () => {
    get('/assets/materialCabinet/api/getMaterialCabinetWaitDepositAssets', {
      deviceId: config.DEVICE_ID,
      relType: user.userType === 0 || user.userType === 1 ? 3 : 4,
    }).then(res => {
      console.log(JSON.stringify(res.data.data));
      if (res.data) {
        setProducts(res.data.data);
        if (user.userType === 0 || user.userType === 1) {
          if (res.data.data && res.data.data.length == 0) {
            props.checkBoxManager &&
              props.checkBoxManager(manager => {
                if (manager) {
                  Alert.alert('提示', '您没有待归还的设备', [
                    {text: '退出', onPress: () => props.navigation.goBack()},
                    {
                      text: '管理员存放',
                      onPress: () => {
                        setManager(true);
                      },
                    },
                  ]);
                } else {
                  props.navigation.goBack();
                  Dialog.show({
                    type: ALERT_TYPE.DANGER,
                    title: '提醒',
                    textBody: '您没有待归还的设备',
                    closeOnOverlayTap: true,
                    autoClose: 2000,
                  });
                }
              });
            return;
          }
        }
      } else {
        setProducts([]);
      }
    });
  };

  const renderItem = ({item, index}, flex) => {
    if (item) {
      return (
        <View
          style={{
            width: '95%',
            marginLeft: 10,
            marginTop: 10,
            alignItems: 'stretch',
            borderWidth: 2,
            borderColor: '#aaa',
            borderRadius: 8,
            flex,
          }}>
          <View
            style={{
              position: 'absolute',
              top: 0,
              right: 0,
              backgroundColor: item.relState ? '#22895B' : '#C1C0BF',
              borderBottomLeftRadius: 15,
              width: 40,
              height: 30,
            }}>
            <Text
              style={{
                textAlign: 'center',
                fontSize: 15,
                fontWeight: 'bold',
                color: 'white',
              }}>
              {item.relNum}
            </Text>
          </View>

          <Row style={{marginTop: 10, flex: 1}} />
          <LinearGradient
            colors={[
              item.relState ? '#027042' : '#626060',
              item.relState ? '#53AF82' : '#C7C7C7',
            ]}
            start={{x: 0, y: 0}}
            end={{x: 1, y: 0}}
            style={{marginTop: 0}}>
            <ColorButton
              style={{fontSize: 15, fontWeight: 'bold'}}
              backgroundColor={'transparent'}
              height={30}
              onPress={async () => {
                console.log('item', item);
                if (item.relState) {
                  ToastAndroid.show('已存放', ToastAndroid.SHORT);
                } else {
                  checkAndOpenBox(item);
                }
              }}>
              {item.relState ? '已存放' : '空闲'}
            </ColorButton>
          </LinearGradient>
        </View>
      );
    } else {
      return (
        <View
          style={{
            width: '95%',
            marginLeft: 10,
            marginTop: 10,
            alignItems: 'stretch',
            borderWidth: 2,
            borderColor: '#aaa',
            borderRadius: 8,
            flex,
            overflow: 'hidden',
          }}
        />
      );
    }
  };

  const renderContent = () => {
    return (
      <View style={{flex: 1, width: '100%', alignItems: 'stretch'}}>
        {props.data.length > 0 ? (
          <Row style={{flex: 1, marginTop: 60}}>
            <View style={{flex: 1}}>
              {renderItem({item: props.data[0], index: 0}, 6)}
              {renderItem({item: props.data[1], index: 0}, 2)}
              {renderItem({item: props.data[2], index: 0}, 2)}
              {renderItem({item: props.data[3], index: 0}, 2)}
            </View>
            {[0, 1, 2, 3, 4].map(value => {
              return (
                <View style={{flex: 1}}>
                  {props.data
                    .slice(12 * value + 4, 12 * value + 4 + 11)
                    .map((item, index) => {
                      return renderItem(
                        {item: item, index: 12 * value + 4 + index},
                        1,
                      );
                    })}
                  {renderItem(
                    {
                      item: props.data[12 * value + 4 + 11],
                      index: 12 * value + 4 + 11,
                    },
                    2,
                  )}
                </View>
              );
            })}
          </Row>
        ) : null}
      </View>
    );
  };

  const checkAndOpenBox = async item => {
    let value = parseInt(`${item.number}`, 10).toString(16);
    if (value.length === 1) {
      value = '0' + value;
    }
    try {
      props.whetherBoxIsLock(item.address, value, open => {
        if (open) {
          ToastAndroid.show('需要先把柜门关上', ToastAndroid.SHORT);
        } else {
          ToastAndroid.show('存放完成请记得关闭柜门', ToastAndroid.SHORT);
          setTimeout(() => {
            props.openBox(item, () => {
              ModalViewUtil.showFromCenter(
                <BoxManageView2
                  box={item}
                  relType={manager ? 4 : 3}
                  checkBox={callback => {
                    props.whetherBoxIsLock(item.address, value, p => {
                      callback(p);
                    });
                  }}
                  onSavePressed={async params => {
                    try {
                      const {data} = await get(
                        '/assets/materialCabinet/api/getMaterialCabinetCanDepositAssets',
                        {
                          relId: item.relId,
                          warehousingId: params.warehousingId,
                          relType: params.relType,
                        },
                      );
                      props.whetherBoxIsLock(item.address, value, async o => {
                        if (o) {
                          ToastAndroid.show(
                            '请先关闭柜门再保存',
                            ToastAndroid.SHORT,
                          );
                        } else {
                          try {
                            await post(
                              '/assets/materialCabinet/api/materialCabinetDeposit',
                              {...params},
                              true,
                            );
                            ToastAndroid.show('存放成功', ToastAndroid.SHORT);
                            ModalViewUtil.dismissBottomView();
                            props.loadData();
                            // BlobUtils.snapUpload(
                            //   getBaseURL() + '/file/file/api/single?route=file',
                            //   async (filePreviewPathFull: string) => {
                            //     await post(
                            //       '/assets/materialCabinet/api/materialCabinetDeposit',
                            //       {...params, picStr: filePreviewPathFull},
                            //       true,
                            //     );
                            //     ToastAndroid.show(
                            //       '存放成功',
                            //       ToastAndroid.SHORT,
                            //     );
                            //     ModalViewUtil.dismissBottomView();
                            //     props.loadData();
                            //   },
                            // );
                          } catch (error) {
                            ToastAndroid.show(
                              error.message,
                              ToastAndroid.SHORT,
                            );
                          }
                        }
                      });
                    } catch (error) {
                      ToastAndroid.show(error.message, ToastAndroid.SHORT);
                    }
                  }}
                />,
                true,
              );
            });
          }, 300);
        }
      });
    } catch (error) {
      ToastAndroid.show(error.message, ToastAndroid.SHORT);
    }
  };

  return <View style={{flex: 1}}>{renderContent()}</View>;
};

export default withSerialPort(BoxManagePage);
